var server_host = "http://127.0.0.1:8888"
var alipay_url = "https://qr.alipay.com/5734546795641850"
var qrcode_tips = "付费"
//****************** tool *****************
function parse_url(url){
    var a = document.createElement('a')
    a.href=url
    return a
}

//*********** event ************

$(document).on('mouseenter', '.order-array td.ele.unlock', function(e){
    d3.select(this).selectAll('.change_num').style("visibility", 'inherit')
})
$(document).on('mouseleave',  '.order-array td.ele.unlock', function(e){
    d3.select(this).selectAll('.change_num').style("visibility", 'hidden')
})
$(document).on('click', '.order-array td.ele.unlock .change_num', function(e){

    var _ele_this = d3.select(this)
    var _ele_td = d3.select(this.parentNode)
    var _ele_tr = d3.select(this.parentNode.parentNode)
    var _ele_th = _ele_tr.select('.user-name')
    var _ele_table = d3.select(this.parentNode.parentNode.parentNode.parentNode)
    var _ele_head_th = _ele_table.select('thead tr .x-' + _ele_td.attr('x'))
    var shop_div_selector = d3.select(this.parentNode.parentNode.parentNode.parentNode.parentNode)

    var user_name = _ele_th.text()
    var menu_name = _ele_head_th.attr('name')
    var menu_unit = Number(_ele_head_th.attr('unit'))
    var menu_amount = Number(_ele_this.attr('value'))

    var encode_url = encodeURIComponent(shop_div_selector.attr('shop_url'))

    if (!Number(_ele_td.select('.num').text()) && menu_amount < 0){
        return ;
    }

    var menu_list = [{
        'name': menu_name,
        'unit': menu_unit,
        'amount': menu_amount
    }]
    var server_adencode_url = server_host + "/api/py/add_menu?name="
        + encodeURIComponent(user_name)
        + "&menu="
        + encodeURIComponent(JSON.stringify(menu_list))
        + "&shop_url="
        + encode_url

    $.get(server_adencode_url)
        .then(function(){
            var shop_div = shop_div_selector
            create_shop_div(shop_div)
        })

})

$(document).on('click', '.menu-status.lock', function(e){
    var shop_div = d3.select(this.parentNode)
    var least_deliver = Number(shop_div.attr('least_deliver'))
    var all_amount = Number(shop_div.select('.order-array .all-amount').attr('sum'))
    if(all_amount < least_deliver){
        alert('低于起送价 无法下单')
        return;
    }
    $.get(
        server_host + '/api/py/split_menu/create',
        {'shop_url': encodeURIComponent(shop_div.attr('shop_url'))}
    ).success(function(strData){
            alert('错定成功！')
            create_shop_div(shop_div)
        })
})

$(document).on('click', '.menu-status.unlock', function(e){
    var shop_div = d3.select(this.parentNode)
    $.get(
        server_host + '/api/py/split_menu/clean',
        {'shop_url': encodeURIComponent(shop_div.attr('shop_url'))}
    ).success(function(strData){
            alert('解锁成功！')
            create_shop_div(shop_div)
        })
})

//*********************  fill data *************************

var fill_table = function(data, table_name, ele_status) {
    // table
    var tab = d3.select(table_name)
    // title
    var head_tr = tab.select('tr')
    head_tr.append("th")
    head_tr.selectAll("th.menu-name")
        .data(data['menu_names'])
        .enter()
        .append('th')
        .attr('class', function(d, i) {
            return 'menu-name x-' + i
        })
        .attr('unit', function(d, i){
            return d[1]
        })
        .attr('name', function(d, i){
            return d[0]
        })
        .text(function(d, i){
            return d[0] +'(' + d[1] + ')';
        });
    head_tr.append('th')
        .attr('class', 'x-all')
        .text('合计')
    head_tr.append('th')
        .attr('class', 'x-discount')
        .text('折扣后')
    // body
    var body = tab.select('tbody')
    //line
    var body_tr = body.selectAll('tr.user-data')
        .data(data['user_names'])
        .enter()
        .append('tr')
        .attr('y', function(d, i){
            return i;
        })
        .attr('class', 'user-data')
    //line title
    body_tr.append('th')
        .attr('class', 'user-name')
        .text(function(d, i){
            return d;
        });
    // element
    var ele_td = body_tr.selectAll('td.ele')
        .data(function(d, i){
            return data['matrix'][i];
        })
        .enter()
        .append('td')
        .attr('class', function(d, i) {
            return  'ele '+ ele_status + " x-" + i
        })
        .attr('x', function(d, i){
            return i
        })
    ele_td.append('a')
        .attr('class', 'dip-num change_num')
        .attr('value', '-1')
        .attr('href', 'javascript:;')
        .text('-')
    ele_td.append('a')
        .attr('class', 'num')
        .text(function(d, i){
            if(d == 0)
                return ""
            else
                return d;
        });
    ele_td.append('a')
        .attr('class', 'add-num change_num')
        .attr('value', '1')
        .attr('href', 'javascript:;')
        .text('+')

    body_tr.append('td')
        .attr('class', 'x-amount')
        .attr('amount', function(d, i){
            var my_tr = d3.select(this.parentNode)
            var amount  = 0
            my_tr.selectAll('td.ele')
                .each(function() {
                    amount += Number(d3.select(this).select('.num').text())
                });
            return amount;
        })
        .attr('sum', function(d, i){
            var my_tr = d3.select(this.parentNode)
            var sum = 0
            my_tr.selectAll('td.ele')
                .each(function() {
                    var num = Number(d3.select(this).select('.num').text())
                    var x_val = d3.select(this).attr('x')
                    var x_th = head_tr.select("th.x-" + x_val)
                    sum += Number(x_th.attr('unit')) * num
                });
            return sum;
        })
        .text(function(){
            var i = d3.select(this)
            return i.attr('amount') + '(￥' + i.attr('sum') +  ')'
        })
    var amount_tr = body.append('tr')
        .attr('class', 'user-amount')
    amount_tr.append('th')
        .attr('class', 'y-all')
        .text('合计')
    amount_tr.selectAll('td.y-amount')
        .data(data['menu_names'])
        .enter()
        .append('td')
        .attr('class', 'y-amount')
        .attr('amount', function(d, i){
            var amount = 0
            body_tr.selectAll('td.ele.x-' + i)
                .each(function() {
                    amount += Number(d3.select(this).select('.num').text())
                })
            return amount;
        })
        .attr('sum', function(d, i) {
            var sum = 0
            body_tr.selectAll('td.ele.x-' + i)
                .each(function() {
                    var num = Number(d3.select(this).select('.num').text())
                    sum += d[1] * num
                })
            return sum;
        })
        .text(function(){
            var i = d3.select(this)
            return i.attr('amount') + '(￥' + i.attr('sum') +  ')'
        });
    var all_amount_tr = amount_tr.append('td')
        .attr('class', 'all-amount')
        .attr('amount', function(){
            var amount = 0
            amount_tr.selectAll('td.y-amount').each(function () {
                amount += Number(d3.select(this).attr('amount'))
            })
            return amount
        })
        .attr('sum', function() {
            var sum = 0
            amount_tr.selectAll('td.y-amount').each(function () {
                sum += Number(d3.select(this).attr('sum'))
            })
            return sum
        })
        .text(function(){
            var i =  d3.select(this)
            return i.attr('amount') + '(￥' + i.attr('sum') +  ')'
        })
    return tab
}
//*********************   ********************
function fill_shop_div(d) {
    var shop_div_symbol = '#shopdiv-' + parse_url(d['url']).pathname.split("/").slice(-1);
    var encode_url = encodeURIComponent(d['url'])
    $.get(server_host + '/api/py/today_order_form?shop_url=' + encode_url).success(function(strData){
        var data = JSON.parse(strData)
        // table
        $.get(server_host + '/api/py/split_menu/show?shop_url=' + encode_url).success(function(strData){
            var status_btn = $(shop_div_symbol + ' .menu-status')
            var ele_status = strData===""?'unlock':'lock';
            //order table
            var tab = fill_table(data, shop_div_symbol  + ' .order-array', ele_status)

            if(ele_status==="unlock"){
                status_btn.removeClass("unlock")
                status_btn.addClass("lock")
                status_btn.val("锁")
            }
            else {
                status_btn.removeClass("lock")
                status_btn.addClass("unlock")
                status_btn.val("解锁")
                var split_data = JSON.parse(strData)
                var split_table = d3.select(shop_div_symbol + " .split-array")
                //---------------------    discount    -------------
                var discount_rate = d3.select(shop_div_symbol + ' .discount_rate')
                discount_rate.text(split_data['discount_rate'])
                tab.select('tbody').selectAll('tr.user-data').append('td')
                    .attr('class', 'x-discount')
                    .attr('discount', function(){
                        var my_tr = d3.select(this.parentNode)
                        var sum = Number(my_tr.select('.x-amount').attr('sum'))
                        return Math.ceil( sum * split_data['discount_rate'] * 10 )/10.0
                    })
                    .text(function(d){
                        var i = d3.select(this)
                        return '￥' + i.attr('discount')
                    })
                //---------------------- cost -----------------------
                var cost = d3.select(shop_div_symbol + ' .cost')
                cost.text(split_data['cost'])
                //----------------------     table       -------------
                // title
                var split_head_tr = split_table.select('thead')
                    .select('tr')
                split_head_tr.append('th')
                split_head_tr.selectAll('th.menu-name')
                    .data(split_data['menu_names'])
                    .enter()
                    .append('th')
                    .attr('class', function(d, i){
                        return 'menu-name x-' + i
                    })
                    .attr('unit', function(d){
                        return d[1]
                    })
                    .text(function(d, i){
                        return d[0] + '(' + d[1] + ')'
                    })
                split_head_tr.append('th')
                    .attr('class', 'x-all')
                    .text('合计')
                //body
                var split_body_tr = split_table.select('tbody')
                    .selectAll('tr.split-index')
                    .data(split_data['fuck_js'])
                    .enter()
                    .append('tr')
                    .attr('class', function(d, i){
                        return 'split-index y-' + i
                    })
                split_body_tr.append('th')
                    .text(function(d){
                        return '订单' + (d + 1)
                    })
                split_body_tr.selectAll('td.ele')
                    .data(function(d, i){
                        return split_data['matrix'][i]
                    })
                    .enter()
                    .append('td')
                    .attr('class', 'ele')
                    .attr('x', function(d, i){
                        return i
                    })
                    .attr('value', function(d){
                        return d
                    })
                    .text(function(d){
                        if(!d)
                            return ''
                        return d
                    })
                split_body_tr.append('td')
                    .attr('class', 'x-amount')
                    .attr('amount', function(d, i){
                        var my_tr = d3.select(this.parentNode)
                        var amount  = 0
                        my_tr.selectAll('td.ele')
                            .each(function() {
                                amount += Number(d3.select(this).text())
                            });
                        return amount;
                    })
                    .attr('sum', function(d, i){
                        var my_tr = d3.select(this.parentNode)
                        var sum = 0
                        my_tr.selectAll('td.ele')
                            .each(function() {
                                var num = Number(d3.select(this).text())
                                var x_val = d3.select(this).attr('x')
                                var x_th = split_head_tr.select("th.x-" + x_val)
                                sum += Number(x_th.attr('unit')) * num
                            });
                        return sum;
                    })
                    .text(function(){
                        var i = d3.select(this)
                        return i.attr('amount') + '(￥' + i.attr('sum') +  ')'
                    })
            }
        });



    })
};

function create_shop_div(shop_div){
    $(shop_div.node().childNodes).remove()
    //add discount label
    var label = shop_div.append('label')
    label.append('a')
        .text('今日折扣: ')
    label.append('a')
        .attr('class', 'discount_rate')
    //add cost label
    var p_tag = shop_div.append('p')
    p_tag.append('a')
        .text('配送费: ')
    p_tag.append('a')
        .attr('class', 'cost')
    // add empty table
    var order_tables = shop_div.append('table')
        .attr('class', 'order-array table table-striped')
    order_tables.append('thead')
        .append('tr')
    order_tables.append('tbody')
    //add lock button
    shop_div.append('input')
        .attr('type', 'button')
        .attr('class', 'menu-status')
    //add empty table
    var split_tables = shop_div.append('table')
        .attr('class', 'split-array table table-striped')
    split_tables.append('thead')
        .append('tr')
    split_tables.append('tbody')

    shop_div.each(function(d){
        fill_shop_div(d);
    })
}